package com.ifinc.common.socket.common_socket;


import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketManager {
    /**
     * @param args
     * @throws java.io.IOException
     */
    public static void main(String[] args) {
        SocketManager manager = new SocketManager();
        manager.doListen();
    }

    public void doListen() {
        ServerSocket server;
        try {
            server = new ServerSocket(9991);
            while (true) {
                Socket client = server.accept();
                new Thread(new SSocket(client)).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //服务器进程
    class SSocket implements Runnable {

        Socket client;

        public SSocket(Socket client) {
            this.client = client;
        }

        public void run() {
            DataInputStream input;
            DataOutputStream output;
            try {
                input = new DataInputStream(client.getInputStream());
                output = new DataOutputStream(client.getOutputStream());
                //
                int len = input.readUnsignedShort();
                System.out.println("len = " + len);
                byte[] bb = new byte[len];
                input.readFully(bb);
                String param = new String(bb);
                System.out.println("param = " + param);
//                byte[] bb = new byte[2];
//                input.readFully(bb);
//                String str = new String(bb);
               String result = "OK";

                output.writeShort(2);
                output.write(result.getBytes());
                output.flush();
                output.close();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    client.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}


